var fs = require('fs');
var path = require('path');
var crypto = require('crypto');

var exportName = process.argv[3];
var dirName = process.argv[2];
var mkdir = function(path) {
	try {
		fs.mkdirSync(path);
	} catch (e) {
		if (e.code != 'EEXIST') throw e;
	}
}

//写文件
var writeFile = function(fileName, data) {
	fs.writeFileSync(fileName, data, 'utf-8');
}

var readFile = function(fileName){
	return fs.readFileSync(fileName, 'utf-8');
}

var template = readFile("template/template.txt");
var moduleTemplate = readFile("template/module.txt");
var indexFile = readFile("template/index.html");
var moduleList = "";


function getDeps(file){
	let list2 = file.match(/require(.*)/g);
	let deps = "";
	if(list2){
		for (var i = 0; i < list2.length; i++) {
			let temp = list2[i].split('"');
			let depand = temp[1];
			let name = depand;
			if(depand.indexOf('/') >= 0){
				let tt = depand.split("/");
				name = tt[tt.length - 1];
			}
			deps += '"'+depand+'":'+'"'+name+'",\n';
		}	
	}
	return deps;
}
//"../../main/MainUtil": "MainUtil",
function parseFile(fileName) {
	let file = readFile(fileName);

	let deps = getDeps(file);

	let list = fileName.split("\\");
	let fName = list[list.length - 1]
	let moduleName = fName.split(".")[0];

	file = moduleTemplate.replace("$content$",file);
	file = file.replace("$moduleName$",moduleName);
	file = file.replace("$deps$",deps);
	moduleList += '"'+moduleName+'",';
	return file;
}

function readDir(dir) {
	var stat = fs.statSync(dir);
	if (!stat.isDirectory()) {
		return "";
	}
	var subpaths = fs.readdirSync(dir),contents = "",
		subpath;
	for (var i = 0; i < subpaths.length; ++i) {
		if (subpaths[i][0] === '.') {
			continue;
		}
		subpath = path.join(dir, subpaths[i]);
		stat = fs.statSync(subpath);
		if (stat.isDirectory()) {
			contents += readDir(subpath);
		} else if (stat.isFile()) {
			contents += parseFile(subpath);
		}
	}
	return contents;
}

function parse(dirName,exportDir,exportName){
	moduleList = "";
	var contents = readDir(dirName);
	// console.log(" contents ",contents);
	let out = template.replace("$classMap$",contents);
	out = out.replace("$moduleList$",moduleList);
	// mkdir(exportDir);
	let md5 = crypto.createHash('md5').update(out).digest('hex');
	console.log("md5 =========== ",md5," exportName ",exportName);
	let fileName = exportName+"_"+md5+".js"
	let path = exportDir + fileName
	writeFile(path,out);
	indexFile = indexFile.replace("$"+exportName+"$",fileName);
	
	return path;
}

function outIndex(exportDir){
	writeFile(exportDir+"index.html",indexFile);
}


if(dirName && exportName){
	parse(dirName,exportName);
	console.log(" buildjs finish")
}
exports.outIndex = outIndex;
exports.parse = parse;
exports.mkdir = mkdir;